package com.youkeda.test.http;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

/**
 * @author CoderXshuai
 */
public class ApiAsker {

    public static void main(String[] args) {
        String url = "https://style.youkeda.com/img/ham/course/py2/h.txt";
        ApiAsker asker = new ApiAsker();
        String content = asker.getContent(url);
        System.out.println("文件内容：" + content);
        try {
            File file = new File("h.txt");
            FileWriter writer = new FileWriter(file);
            writer.write(content);
            System.out.println("下载成功");
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据输入的url，读取页面内容并返回
     */
    public String getContent(String url) {
        // okHttpClient 实例
        OkHttpClient okHttpClient = new OkHttpClient();
        // 定义一个request
        Request request = new Request.Builder().url(url).build();
        // 返回结果字符串
        String result = null;
        try {
            // 执行请求
            Response response = okHttpClient.newCall(request).execute();
            // 获取响应内容
            result = response.body().string();
        } catch (IOException e) {
            // 抓取异常
            System.out.println("request " + url + " error . ");
            e.printStackTrace();
        }
        return result;
    }
}
